import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:get/get.dart';
import 'package:jxchmz/%E8%93%9D%E7%89%99/BleManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/HexToInt.dart';

import 'BleModel.dart';

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => new _SettingState();
}

class _SettingState extends State<Setting> {
  TextEditingController PowerController = new TextEditingController();
  double _sliderValue = 1;
  BluetoothCharacteristic? _bluetoothCharacteristicFFF1 ;
  BluetoothCharacteristic? _bluetoothCharacteristicFFF2 ;


//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero,(){
      //获取当前功率
      _bluetoothCharacteristicFFF1 = BleModel.BletoothCharacteristicFFF1;
      _bluetoothCharacteristicFFF2 = BleModel.BletoothCharacteristicFFF2;
      print("_bluetoothCharacteristicFFF2:$_bluetoothCharacteristicFFF2");
      //设置监听蓝牙数据
      _characteristicFFF4SetNotify();
    });

  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print("关闭设置页面");
    _bluetoothCharacteristicFFF1!.setNotifyValue(false);
    BleManager.instance.CancelListen();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text("SetPower".tr, style: TextStyle(fontSize: 15, color: Colors.black),),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
              color: Colors.black
          ),
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child: Column(
            children: [
              //功率显示
              TextField(
                controller: PowerController,
                enabled: false,
                decoration: InputDecoration(
                  hintText: "Power".tr,
                    icon: Container(
                      width:70,
                      child: Text("Power".tr),
                    )
                ),
              ),
              //进度调整功率
              Slider(
                value: _sliderValue,
                min: 1,
                max: 33,
                onChanged: (v){
                  print("当前功率:$v");
                  setState(() {
                    _sliderValue = v;
                    PowerController = new TextEditingController(text: _sliderValue.toInt().toString());
                  });
                },
              ),
              Spacer(),
              MaterialButton(
                minWidth: MediaQuery.of(context).size.width-100,
                  onPressed: (){
                    SetPower(_sliderValue);
                // Get.back();
              },
              color: Colors.blue,
                child: Text("sure".tr,style: TextStyle(color: Colors.white),),
              )
            ],
          ),
        )
    );
  }
  //监听特征上报数据
  _characteristicFFF4SetNotify() async {
    await   _bluetoothCharacteristicFFF1!.setNotifyValue(true);
    // ignore: missing_return
    BleManager.instance.listenCharacteristicValue(_bluetoothCharacteristicFFF1!, (data) async {
      if (data == null) {
        print("data=null>>>>>>");
        return;
      }

      //解析蓝牙数据，转为十六进制
      String DataHex =await _BleDataCallback(data);
      List dataList = DataHex.split(",");
      print("设置页面功率数据:$dataList");
      if(dataList[0]=="f0"&&dataList[1]=="22"&&dataList[2]=="06"){
        _sliderValue = HexToInt().hexToInt(dataList[10].toString()).toDouble();
        PowerController = new TextEditingController(text: _sliderValue.toInt().toString());
      }
      if(dataList[0]=="f0"&&dataList[1]=="03"&&dataList[2]=="04"&&dataList[3]=="00"){
        //关闭页面
        Get.back();
        GetxTools().SuccessToast("SetSuccess".tr);
      }if(dataList[0]=="f0"&&dataList[1]=="03"&&dataList[2]=="04"&&dataList[3]=="11"){
        GetxTools().ErrorToast("SetFail".tr);
      }
      setState(() {
      });
    });
//获取当前功率
    GetPower();
  }
  //  发送请求
  void WriteBle(WritData) {
    // print("发送的蓝牙数据:${WritData}");
    BleManager.instance.characteristicToWriteValue(_bluetoothCharacteristicFFF2!, WritData).then((value) => print("write result:$value"));
  }
  //解析蓝牙数据
  _BleDataCallback(value) async {
    List data = [];
    for (var i = 0; i < value.length; i++) {
      String dataStr = value[i].toRadixString(16);
      if (dataStr.length < 2) {
        dataStr = "0" + dataStr;
      }
      String dataEndStr =  dataStr;
      data.add(dataEndStr);
    }
    return data.join(",");
  }
  //校验位
  int checkSum(List<int> buffer) {
    int sum = 0;
    for (int i = 0; i < buffer.length; i++) {
      sum += buffer[i];
    }
    sum = (~sum) + 1;
    return sum;
  }
  //获取当前功率
  GetPower(){
    List<int> WritData = [0x40,0x02,0x06,0xB8];
    WriteBle(WritData);
  }
  //设置功率
SetPower(double PowerValue){
  List<int> WritData = [0x40,0x03,0x04];
   String Hex ="0x"+PowerValue.toInt().toRadixString(16);
  WritData.add(int.parse(Hex));
  //校验位
  int Check = checkSum(WritData);
  WritData.add(Check);
  WriteBle(WritData);
}

}
